package wifiunion.com.notice.widget.treedialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wifiunion.com.notice.BasePresenter;
import wifiunion.com.notice.CommonUtils;
import wifiunion.com.notice.Constants;
import wifiunion.com.notice.R;
import wifiunion.com.notice.entity.User;
import wifiunion.com.notice.utils.SharedPreferencesUtils;
import wifiunion.com.notice.widget.treedialog.adapter.SimpleTreeAdapter;
import wifiunion.com.notice.widget.treedialog.adapter.TreeListViewAdapter;
import wifiunion.com.notice.widget.treedialog.entity.Node;
import wifiunion.com.notice.widget.treedialog.entity.TreeEntity;

/**
 * Created by Administrator on 2017/6/7.
 * 树状结构选择对话框
 */

public class TreefilterDialog extends Dialog implements View.OnClickListener, TreefilterContact.View {

    private TextView titleName;


    private TextView cancelTxt, confirmTxt;

    private TreefilterPresenter mTreefilterPresenter;


    private Context mContext;

    private Activity mActivity;


    private TreefilterCallback mTreefilterCallback;


    private ListView mListView;

    private String mUuid;

    private String mAuthtoken;

    /**
     * 初始数据
     */
    private List<TreeEntity> mOriginData = new ArrayList<TreeEntity>();

    /**
     * 处理后的数据
     */
    private List<TreeEntity> mOperatorData = new ArrayList<TreeEntity>();

    private HashMap<String, Object> mParams = new HashMap<>();

    private TreeListViewAdapter mAdapter;

    public ArrayList<String> mSelectTree = new ArrayList<>();


    public String mCommunityUuid;
    /**
     * 对话框类型
     * 0 选择
     * 1 展示文件全路径的
     */
    private int mDialogtype;
    /**
     *
     */
    private HashMap<String, String> mPidMap = new HashMap<>();


    public TreefilterDialog(Context context, Activity activity, String uuid, TreefilterCallback tfc, String communityUuid, int dialogpagetype) {
        super(context, R.style.alert_dialog);
        mActivity = activity;
        mUuid = uuid;
        mContext = context;
        mTreefilterCallback = tfc;
        mDialogtype = dialogpagetype;
        mCommunityUuid = communityUuid;
        LayoutInflater li = LayoutInflater.from(context);
        ViewGroup contentView = (ViewGroup) li.inflate(
                R.layout.dialog_tree, null);
        contentView.bringToFront();

        mListView = (ListView) contentView.findViewById(R.id.dialog_tree_listview);
        cancelTxt = (TextView) contentView.findViewById(R.id.cancel_txt);
        confirmTxt = (TextView) contentView.findViewById(R.id.confirm_txt);
        titleName = (TextView) contentView.findViewById(R.id.tv_title_name);


        cancelTxt.setOnClickListener(this);
        confirmTxt.setOnClickListener(this);

        titleName.requestFocus();
        mAuthtoken = SharedPreferencesUtils.getSharedPreferences(Constants.CONFIG_AUTHTOKEN, context);


        setCanceledOnTouchOutside(true);
        setContentView(contentView);

        if (mDialogtype == 0) {
            setData();
            confirmTxt.setVisibility(View.VISIBLE);
        } else {
            getCurrentData();
            confirmTxt.setVisibility(View.GONE);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = getContext().getResources().getDimensionPixelSize(
                R.dimen.dp_480);
        lp.height = (int) (CommonUtils.getScreenHeight(getContext()) * 0.9f);
        lp.gravity = Gravity.CENTER;
        getWindow().setAttributes(lp);
    }

    public void setTitleMsg(String msg) {
        if (titleName != null) {
            titleName.setText(msg);
        }
    }


    @Override
    public void onClick(View v) {

        int i = v.getId();
        if (i == R.id.cancel_txt) {
            dismiss();

        } else if (i == R.id.confirm_txt) {
            if (mTreefilterCallback != null) {
                responseSelectData();
            }
            dismiss();

        }

    }

    /**
     * 回调
     */
    private void responseSelectData() {
        for (Node nd : (List<Node>) (mAdapter.getAllNodes())) {

            if (nd.getChecked() == 1 && !mSelectTree.contains(nd.getId())) {
                mSelectTree.add(nd.getId());
            }
        }
        mTreefilterCallback.onComfirmClicked(mSelectTree);

    }


    private void initListView() {
        try {
            if (mDialogtype == 0) {
                mAdapter = new SimpleTreeAdapter<TreeEntity>(mListView, getContext(), mOperatorData, 0, mDialogtype);
            } else {
                mAdapter = new SimpleTreeAdapter<TreeEntity>(mListView, getContext(), mOperatorData, 10, mDialogtype);
            }
//            mAdapter.setOnTreeNodeClickListener(new SelectMemberListViewAdapter.OnTreeNodeClickListener() {
//                @Override
//                public void onClick(Node node, int position) {
//                    if (node.isLeaf()) {
//                        Toast.makeText(getContext(), node.getName(), Toast.LENGTH_SHORT).show();
//                    }
//
//                }
//
//            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        mListView.setAdapter(mAdapter);
    }


    /**
     * 获取全部路径数据
     */
    private void setData() {
        mTreefilterPresenter = new TreefilterPresenter(this, 0);
        mParams.clear();
        mParams.put("Authorization", mAuthtoken);
        mParams.put("menuUuid", mUuid);
        mTreefilterPresenter.getTreeFilter(mParams);
    }


    private void getCurrentData() {
        mTreefilterPresenter = new TreefilterPresenter(this, 1);
        mParams.clear();
        mParams.put("Authorization", mAuthtoken);
        mParams.put("menuUuid", mUuid);
        mParams.put("communityUuid", mCommunityUuid);
        mTreefilterPresenter.getCurrentTree(mParams);
    }

    @Override
    public void onProgress() {

    }

    @Override
    public void onError(Object obj) {

    }

    @Override
    public void onSuccess(final Object obj) {

        if (obj != null) {
            ArrayList<TreeEntity> list = (ArrayList<TreeEntity>) obj;
            mOriginData.addAll(list);


            for (TreeEntity te : mOriginData) {
                if (te != null && mCommunityUuid.contains(te.getCommunityUuid())) {
                    te.setChecked(1);
                }
            }

            mOperatorData.addAll(mOriginData);
            for (TreeEntity te : mOriginData) {
                TreeEntity subtreeEntity = new TreeEntity(te.getCommunityUuid(), te.getUuid(), te.getName(), Constants.SUB_TREENODE_PREX + te.getUuid());
                if (te != null && mCommunityUuid.contains(te.getCommunityUuid())) {
                    subtreeEntity.setChecked(1);
                }
                mOperatorData.add(subtreeEntity);
            }

            User user = SharedPreferencesUtils.getUserSharedPreferences(mContext);
            TreeEntity ownData = new TreeEntity(user.getCommunityUuid(), "0", "自有数据", "-1");
            if (mCommunityUuid.contains(user.getCommunityUuid())) {
                ownData.setChecked(1);
            }
            mOperatorData.add(0, ownData);

            initListView();
        }
    }

    @Override
    public void getCurrentTreeSuccess(final Object obj) {
        if (obj != null) {
            if (obj != null) {
                ArrayList<TreeEntity> list = (ArrayList<TreeEntity>) obj;
                mOriginData.addAll(list);

                for (TreeEntity te : mOriginData) {

                    if (te != null && mCommunityUuid.contains(te.getCommunityUuid())) {
                        te.setChecked(1);
                    }
                }
                mOperatorData.addAll(mOriginData);


                for (int i = 0; i < mOperatorData.size(); i++) {
                    for (int j = 1; j < mOperatorData.size(); j++) {

                        if ((mOperatorData.get(i) != null && mOperatorData.get(j) != null) && mOperatorData.get(i).getUuid().equals(mOperatorData.get(j).getParentCommunityUuid())) {
                            mOperatorData.get(i).setLeaf(false);
                        }
                    }
                }


                if (mOperatorData.size() <= 1) {

                    User user = SharedPreferencesUtils.getUserSharedPreferences(mContext);
                    if ((mOperatorData.get(0) != null) && mOperatorData.get(0).getCommunityUuid().equals(user.getCommunityUuid())) {

                        //如果是本地数据，显示一个文件图标即可
                    } else {
                        for (TreeEntity te : mOperatorData) {
                            TreeEntity subtreeEntity = new TreeEntity(te.getCommunityUuid(), te.getUuid(), te.getName(), Constants.SUB_TREENODE_PREX + te.getUuid());
                            if (te != null && mCommunityUuid.contains(te.getCommunityUuid())) {
                                subtreeEntity.setChecked(1);
                            }
                            mOperatorData.add(subtreeEntity);
                        }
                    }
                } else {
                    for (TreeEntity te : mOperatorData) {
                        if (te != null && te.isLeaf()) {
                            TreeEntity subtreeEntity = new TreeEntity(te.getCommunityUuid(), te.getUuid(), te.getName(), Constants.SUB_TREENODE_PREX + te.getUuid());
                            mOperatorData.add(subtreeEntity);
                        }
                    }
                }

                initListView();
            }
        }
    }

    @Override
    public void getCurrentTreeFailed(Object obj) {

    }

    @Override
    public void setPresenter(BasePresenter tp) {

    }

}